package cn.layfolk.uaa.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.layfolk.daimao.vo.respvo.ResponseVo;
import cn.layfolk.uaa.domain.OauthClientDetails;
import cn.layfolk.uaa.mapper.OauthClientDetailsMapper;
import cn.layfolk.uaa.service.OauthClientDetailsService;
import cn.layfolk.uaa.vo.AccessTokenInfoDto;
import cn.layfolk.uaa.vo.AddOauthClientDetailInDto;
import cn.layfolk.uaa.vo.ClientModeLoginInDto;
import cn.layfolk.uaa.vo.ClientModeLoginOutDto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 *
 *
 */
@Service
@Slf4j
public class OauthClientDetailsServiceImpl extends ServiceImpl<OauthClientDetailsMapper, OauthClientDetails> implements OauthClientDetailsService {

    @Autowired
    private OauthClientDetailsMapper oauthClientDetailsMapper;

    /**
     * 客户端模式登录，返回access_token
     */
    @Override
    public ClientModeLoginOutDto clientModeLogin(ClientModeLoginInDto inDto) {
        ClientModeLoginOutDto responseVo = new ClientModeLoginOutDto();

        StringBuilder params = new StringBuilder();
        params.append("client_id=").append(inDto.getClientId());
        params.append("&client_secret=").append(inDto.getClientSecret());
        params.append("&grant_type=").append(inDto.getGrantType());
        params.append("&scopes=").append(inDto.getScopes());
        String url = "http://localhost:8888/oauth/token?" + params;
        HttpResponse response = HttpUtil.createPost(url).execute();

        String token = JSONUtil.parseObj(response.body()).get("access_token").toString();

        if (token == null) {
            responseVo.setMessage("登录失败");
            responseVo.setStatusCode(500);
            return responseVo;
        }

        responseVo.setData(token);
        responseVo.setMessage(inDto.getClientId()+"登录成功");
        return responseVo;
    }

    /**
     * 解析AccessInfo
     */
    @Override
    public AccessTokenInfoDto getAccessInfo() throws UnsupportedEncodingException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String authorization = request.getHeader("Authorization");
        String token = authorization.substring(authorization.lastIndexOf(" ")+1);
        token = java.net.URLEncoder.encode(token,"UTF-8");
        HttpResponse response = HttpUtil.createGet("http://localhost:8888/oauth/check_token?token=" + token).execute();
        String content = JSONUtil.parseObj(response.body()).toString();
        return JSONUtil.toBean(content, AccessTokenInfoDto.class);
    }

    @Override
    public ResponseVo addOauthClientDetail(AddOauthClientDetailInDto dto) {
        ResponseVo responseVo = new ResponseVo<>();

        if (dto.getClientId() == null) {
            responseVo.setMessage("ClientId is null");
            responseVo.setStatusCode(500);
            return responseVo;
        }
        QueryWrapper<OauthClientDetails> wrapper = new QueryWrapper<>();
        wrapper.eq("client_id", dto.getClientId());
        if (oauthClientDetailsMapper.selectCount(wrapper) > 0) {
            responseVo.setMessage("ClientId is exist");
            responseVo.setStatusCode(500);
            return responseVo;
        }
        OauthClientDetails clientDetails = new OauthClientDetails();
        BeanUtils.copyProperties(dto, clientDetails, "clientSecret");
        if (dto.getClientSecret() == null) {
            dto.setClientSecret("123456");
        }
        clientDetails.setClientSecret(new BCryptPasswordEncoder().encode(dto.getClientSecret()));
        oauthClientDetailsMapper.insert(clientDetails);
        responseVo.setData(clientDetails);
        responseVo.setMessage("新增OauthClientDetail成功");
        log.info("新增用户"+dto.getClientId()+"成功");
        return responseVo;
    }
}
